﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OrderSystem.Entity;

namespace OrderSystem
{
    static public class UserManager
    {
        static private OrderSystemDBEntities db;
        static public OrderSystemDBEntities Context
        {
            get
            {
                try
                {
                    if (db == null) db = new OrderSystemDBEntities();
                    if (db.Connection.State != System.Data.ConnectionState.Open)
                        db.Connection.Open();
                    return db;
                }
                catch
                {
                    db = null;
                    return Context;
                }
            }
        }

        static public bool VerifyPassword(string Login, string Password)
        {
            return (Context.UsersSets.Single(u => u.login == Login)).password == Password;
        }

        static public bool VerifyUser(string Login)
        {
           return (Context.UsersSets.SingleOrDefault(u => u.login == Login)) != null;
        }


        static public bool AddToBase(object model)
        {
            var m = model as OrderSystem.Models.RegisterModel;
            bool result = (Context.UsersSets.Count(u => u.login == m.UserName) == 0);

            if (result)
            {
                UsersSet user = new UsersSet();
                user.login = m.UserName;
                user.password = m.Password;
                //user.email = m.Email;
                user.role = "Administrator";

                Context.UsersSets.AddObject(user);
                Context.SaveChanges();
            }

            return result;
        }

        static public UsersSet GetFromBase(int Id)
        {
            return Context.UsersSets.Single(u => u.Id == Id);
        }

        static public UsersSet GetFromBase(string Login)
        {
            return Context.UsersSets.Single(u => u.login == Login);
        }

        //static public UsersSet GetFromBase(string Login, OrderSystemDBEntities DB = null)
        //{
        //    if (DB == null) DB = db;
        //    return DB.UsersSets.Single(u => u.login == Login);
        //}

        static public bool Update(int Id)
        {
//            UsersSet = 

            return true;
        }

        static public bool IsInRole(string Login, string Role)
        {

            UsersSet user = GetFromBase(Login);
            if (user == null) return false;
            if (user.role != Role) return false;
            return true;
        }

        static public string GetRole(string Login)
        {
            UsersSet user = GetFromBase(Login);
            if (user == null) return "error";
            return user.role;
        }
    }
}